package com.jbookstore.dao.daoImpl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.jbookstore.dao.UserDao;
import com.jbookstore.dto.UserDto;

public class UserDaoImpl implements UserDao{

	@Autowired private JdbcTemplate jdbcTemplate;
	
	public void insertUser(UserDto userDto) {
	
		StringBuilder sqlSb = new StringBuilder();
		
		sqlSb.append("INSERT INTO member (user_id, name, password, address, phone_num, join_date) VALUES ");
		sqlSb.append("(");
		sqlSb.append("'").append(userDto.getUserId()).append("',");
		sqlSb.append("'").append(userDto.getName()).append("',");
		sqlSb.append("'").append(userDto.getPassword()).append("',");
		sqlSb.append("'").append(userDto.getAddress()).append("',");
		sqlSb.append("'").append(userDto.getPhoneNum()).append("',");
		sqlSb.append("sysdate()");
		sqlSb.append(");");
				
		this.jdbcTemplate.update(sqlSb.toString());
	}
	
	public UserDto selectUser(UserDto userDto) {
		
		StringBuilder sqlSb = new StringBuilder();
		
		sqlSb.append("SELECT * FROM member WHERE ");
		sqlSb.append("user_id='").append(userDto.getUserId()).append("'");
		sqlSb.append(" AND ");
		sqlSb.append("password='").append(userDto.getPassword()).append("'");
			
		RowMapper<UserDto> mapper = new RowMapper<UserDto>() {
		    public UserDto mapRow(ResultSet rs, int rowNum) throws SQLException {
		      UserDto user = new UserDto();
		      user.setUserId(rs.getString("user_id"));
		      user.setName(rs.getString("name"));
		      user.setAddress(rs.getString("address"));
		      user.setPhoneNum(rs.getString("phone_num"));
		      user.setJoinDate(rs.getDate("join_date"));
		      
		      return user;
		    }
		};
		
		return (UserDto) jdbcTemplate.queryForObject(sqlSb.toString(),
				new Object[] {}, mapper);
	}

}



